import {
  login,
  logout,
  getInfo,
  sassLogin
} from '@/api/user'
import {
  getToken,
  setToken,
  removeToken
} from '@/utils/auth'
import router, {
  resetRouter
} from '@/router'
import {
  encryption
} from '@/utils/index'
import {
  setStore,
  getStore,
  removeStore
} from '@/utils/store'

import { Message, Notification } from 'element-ui'

const state = {
  userInfo: getStore({
    name: 'userInfo'
  }) || {},
  permissions: getStore({
    name: 'permissions'
  }) || {},
  roles: getStore({
    name: 'roles'
  }) || [],
  menu: getStore({
    name: 'menu'
  }) || [],
  isInitMenu: getStore({
    name: 'isInitMenu'
  }) || false,
  access_token: getStore({
    name: 'access_token'
  }) || '',
  refresh_token: getStore({
    name: 'refresh_token'
  }) || '',
  tenant_id: getStore({
    name: 'tenant_id'
  }) || ''
}

const mutations = {
  SET_ACCESS_TOKEN: (state, access_token) => {
    state.access_token = access_token
    setStore({
      name: 'access_token',
      content: state.access_token,
      type: 'session'
    })
  },
  SET_USER_INFO: (state, userInfo) => {
    state.userInfo = userInfo
    setStore({
      name: 'userInfo',
      content: state.userInfo,
      type: 'session'
    })
  },
  SET_REFRESH_TOKEN: (state, rfToken) => {
    state.refresh_token = rfToken
    setStore({
      name: 'refresh_token',
      content: state.refresh_token,
      type: 'session'
    })
  },
  SET_TENANT_ID: (state, tenant_id) => {
    state.tenant_id = tenant_id
    setStore({
      name: 'tenant_id',
      content: state.tenant_id,
      type: 'session'
    })
  },
  SET_ROLES: (state, roles) => {
    state.roles = roles
    setStore({
      name: 'roles',
      content: state.roles,
      type: 'session'
    })
  },
  SET_PERMISSIONS: (state, permissions) => {
    const list = {}
    for (let i = 0; i < permissions.length; i++) {
      list[permissions[i]] = true
    }
    state.permissions = list
    setStore({
      name: 'permissions',
      content: state.permissions,
      type: 'session'
    })
  }
}

const actions = {
  // user login
  SassLoginByUsername({
    commit,
    state,
    dispatch
  }, userInfo) {
    return new Promise((resolve, reject) => {
      const user = encryption({
        data: userInfo,
        key: 'samssamssamssams',
        param: ['password'],
        platform: ''
      })
      sassLogin(user.username, user.password, user.platform, user.randomStr).then(response => {
        const data = response
        if (data.code === 0) {
          reject(data.msg)
          Message({
            message: data.msg,
            type: 'error',
            duration: 5 * 1000
          })
        } else {
          // console.log('存token', data.access_token)
          setToken(data.access_token)
          commit('SET_ACCESS_TOKEN', data.access_token)
          commit('SET_REFRESH_TOKEN', data.refresh_token)
          commit('SET_TENANT_ID', data.tenant_id)
          // commit('CLEAR_LOCK')
          resolve()
        }
      }).catch(error => {
        reject(error)
      })
    })
  },
  // sass login
  LoginByUsername({
    commit,
    state,
    dispatch
  }, userInfo) {
    return new Promise((resolve, reject) => {
      const user = encryption({
        data: userInfo,
        key: 'samssamssamssams',
        param: ['password']
      })
      login(user.username, user.password, '1', user.TENANT_ID, user.randomStr).then(response => {
        const data = response
        if (data.code === 0) {
          reject()
          Message({
            message: data.msg,
            type: 'error',
            duration: 5 * 1000
          })
        } else {
          // console.log('platform', user.platform)
          const data = response
          // console.log('存token', data.access_token)
          setToken(data.access_token)
          commit('SET_ACCESS_TOKEN', data.access_token)
          commit('SET_REFRESH_TOKEN', data.refresh_token)
          commit('SET_TENANT_ID', data.tenant_id)
          // commit('CLEAR_LOCK')
          resolve()
        }
      }).catch(error => {
        reject(error)
      })
    })
  },
  // get user info
  GetUserInfo({
    commit,
    state,
    dispatch
  }) {
    // console.log('获取用户详情11111')
    return new Promise((resolve, reject) => {
      getInfo().then(response => {
        // console.log('获取用户详情了啊1111', response)
        // console.log('获取用户详情了啊', response.data)
        const data = response.data
        // console.log(data)

        if (!data) {
          reject(response.msg)
        }

        const {
          roles,
          sysUser,
          permissions
        } = data

        // console.log(roles, sysUser, permissions)

        // roles must be a non-empty array
        if (!roles || roles.length <= 0) {
          reject('getInfo: roles must be a non-null array!')
        }
        commit('SET_ROLES', roles)
        commit('SET_USER_INFO', sysUser)
        commit('SET_PERMISSIONS', permissions)
        resolve(response)
      }).catch(error => {
        // console.log('请求详情', error)
        reject(error)
      })
    })
  },
  // user logout
  LogOut({
    commit,
    state
  }) {
    return new Promise((resolve, reject) => {
      commit('SET_MENU', [])
      commit('SET_PERMISSIONS', [])
      commit('SET_USER_INFO', {})
      commit('SET_ACCESS_TOKEN', '')
      commit('SET_REFRESH_TOKEN', '')
      commit('SET_ROLES', [])
      commit('tags/DEL_ALL_TAG', {}, { root: true })
      removeToken()
      resolve()
    })
  },
  // 注销session   zhen de
  FedLogOut({
    commit,
    state
  }) {
    return new Promise((resolve, reject) => {
      logout().then((res) => {
        // console.log(res)

        commit('SET_ACCESS_TOKEN', '')
        commit('SET_ROLES', [])
        // 清除权限
        commit('SET_PERMISSIONS', [])
        // 清除用户信息
        commit('SET_USER_INFO', {})
        commit('SET_REFRESH_TOKEN', '')
        commit('SET_ROLES', [])
        commit('tags/DEL_ALL_TAG', {}, { root: true })
        removeToken()
        resolve()
      }).catch(error => {
        reject(error)
      })
    })
  },

  // remove token
  resetToken({
    commit
  }) {
    return new Promise(resolve => {
      commit('SET_ACCESS_TOKEN', '')
      commit('SET_ROLES', [])
      removeToken()
      resolve()
    })
  },

  // dynamically modify permissions
  changeRoles({
    commit,
    dispatch
  }, role) {
    return new Promise(async resolve => {
      const token = role + '-token'

      commit('SET_ACCESS_TOKEN', token)
      setToken(token)

      const {
        roles
      } = await dispatch('getInfo')

      resetRouter()

      // generate accessible routes map based on roles
      const accessRoutes = await dispatch('permission/generateRoutes', roles, {
        root: true
      })

      // dynamically add accessible routes
      router.addRoutes(accessRoutes)

      // reset visited views and cached views
      dispatch('tagsView/delAllViews', null, {
        root: true
      })

      resolve()
    })
  },
  SET_MENU: (state, menu) => {
    state.menu = menu
    setStore({
      name: 'menu',
      content: state.menu,
      type: 'session'
    })
  }
}

export default {
  namespaced: true,
  state,
  mutations,
  actions
}
